<template>
  <view class="card-key-goods">
    <!-- 商品规格选择 -->
    <view class="product-duration-section" v-if="goodsInfo.specs && goodsInfo.specs.length > 0">
      <text class="section-title">商品规格</text>
      <view class="option-buttons">
        <view 
          class="option-btn" 
          :class="{ active: selectedSpec && selectedSpec.id === spec.id }" 
          @click="selectSpec(spec)"
          v-for="spec in goodsInfo.specs" 
          :key="spec.id"
        >
          <text class="option-text">{{ spec.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 卡密售价选择 -->
    <view class="carmine-price-section" v-if="selectedSpec">
      <text class="section-title">寄售卡密列表</text>
      <view class="carmine-options" v-if="getCarmineOptions().length > 0">
        <view 
          class="carmine-option" 
          :class="{ active: isSelected(carmine) }"
          @click="selectCarmine(carmine)"
          v-for="carmine in getCarmineOptions()" 
          :key="`${carmine.end_time}_${carmine.price}`"
        >
          <view class="carmine-info">
            <text class="carmine-price">价格：{{ carmine.price }}</text>
            <text class="carmine-stock">库存: {{ carmine.allcount }}</text>
            <text class="carmine-expire" v-if="carmine.end_time !== '0'">{{ getExpireText(carmine.end_time) }}</text>
          </view>
        </view>
      </view>
      <view class="no-carmine-data" v-else>
        <image class="no-data-icon" src="/static/Images/common/Zanwu.png" mode="aspectFit"></image>
        <text class="no-data-text">暂无该规格的库存商品数据！</text>
      </view>
    </view>
    
    <!-- 购买数量 -->
    <view class="quantity-section">
      <text class="section-title">购买数量</text>
      <view class="quantity-control">
        <view class="quantity-btn" @click="decreaseQuantity">
          <text class="quantity-btn-text">-</text>
        </view>
        <text class="quantity-btn-text">|</text>
        <text class="quantity-value">{{ quantity }}</text>
        <text class="quantity-btn-text">|</text>
        <view class="quantity-btn" @click="increaseQuantity">
          <text class="quantity-btn-text">+</text>
        </view>
      </view>
    </view>
    
    <!-- 成交记录 -->
    <view class="transaction-section">
      <text class="section-title">成交记录</text>
      <view class="transaction-table">
        <!-- 表头 -->
        <view class="table-header">
          <text class="header-cell time-cell">成交时间</text>
          <text class="header-cell price-cell">价格</text>
          <text class="header-cell duration-cell">耗时</text>
        </view>
        <!-- 表格内容 -->
        <view class="table-body">
          <view class="table-row" v-for="(record, index) in transactionRecords" :key="index" :class="{ 'even-row': index % 2 === 1 }">
            <text class="body-cell time-cell">{{ record.time }}</text>
            <text class="body-cell price-cell">{{ record.price }}</text>
            <text class="body-cell duration-cell">{{ record.duration }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 销售渠道 -->
    <view class="channel-section">
      <text class="section-title">充值渠道</text>
      
      <!-- 支持的平台 -->
      <view class="platform-grid">
        <view 
          class="platform-item" 
          :class="{ supported: goodsInfo.channel_ids && goodsInfo.channel_ids.includes(platform.id), unsupported: !goodsInfo.channel_ids || !goodsInfo.channel_ids.includes(platform.id) }"
          v-for="platform in platformList" 
          :key="platform.id"
        >
          <image 
            class="platform-icon" 
            :src="goodsInfo.channel_ids && goodsInfo.channel_ids.includes(platform.id) ? '/static/Images/goods/Zhichi.png' : '/static/Images/goods/Buzhichi.png'" 
            mode="aspectFit"
          ></image>
          <text class="platform-text">{{ platform.name }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CardKeyGoods',
  props: {
    goodsInfo: {
      type: Object,
      required: true
    },
    initialSelectedSpec: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      selectedSpec: null,
      selectedCarmines: [], // 改为数组支持多选
      quantity: 1,
      platformList: [
        { id: 1, name: '咸鱼' },
        { id: 2, name: '得物' },
        { id: 3, name: '小红书' },
        { id: 4, name: '拼多多' },
        { id: 5, name: '淘宝' },
        { id: 6, name: '京东' },
        { id: 7, name: '抖音' },
        { id: 8, name: '限购' },
        { id: 9, name: 'API充值' }
      ],
      transactionRecords: [
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' }
      ]
    }
  },
  watch: {
    initialSelectedSpec: {
      handler(newVal) {
        if (newVal) {
          this.selectedSpec = newVal;
          this.selectedCarmines = []; // 重置选中的卡密列表
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 如果有规格，默认选择第一个规格
    if (this.goodsInfo.specs && this.goodsInfo.specs.length > 0 && !this.selectedSpec) {
      this.selectedSpec = this.goodsInfo.specs[0];
      this.$emit('spec-change', this.selectedSpec);
    }
    
    // 初始化时向父组件传递数量
    this.emitQuantityChange();
  },
  methods: {
    // 选择商品规格
    selectSpec(spec) {
      this.selectedSpec = spec;
      this.selectedCarmines = []; // 重置选中的卡密列表
      this.$emit('spec-change', spec);
      this.$emit('carmine-change', []);
      // 强制父组件更新价格和库存显示
      this.$nextTick(() => {
        this.$emit('price-stock-update');
      });
    },
    
    // 获取当前规格的卡密选项
    getCarmineOptions() {
      if (!this.goodsInfo.carmines || !this.selectedSpec) {
        return [];
      }
      
      const specId = this.selectedSpec.id;
      const carmineData = this.goodsInfo.carmines[specId];
      const options = [];
      
      if (carmineData) {
        // 遍历carmineData对象，end_time为对象键
        Object.keys(carmineData).forEach(endTime => {
          const priceList = carmineData[endTime];
          if (Array.isArray(priceList)) {
            // 遍历价格列表
            priceList.forEach(item => {
              if (item.price && item.allcount > 0) {
                options.push({
                  price: item.price,
                  allcount: item.allcount,
                  end_time: endTime
                });
              }
            });
          }
        });
      }
      
      // 按价格排序
      return options.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
    },
    
    // 选择卡密（支持多选）
    selectCarmine(carmine) {
      const index = this.selectedCarmines.findIndex(item => 
        item.end_time === carmine.end_time && item.price === carmine.price
      );
      
      if (index > -1) {
        // 如果已选中，则取消选择
        this.selectedCarmines.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedCarmines.push(carmine);
      }
      
      this.$emit('carmine-change', this.selectedCarmines);
      // 强制父组件更新价格和库存显示
      this.$nextTick(() => {
        this.$emit('price-stock-update');
      });
    },
    
    // 获取过期时间文本
    getExpireText(endTime) {
      if (endTime === '0' || endTime === 0) {
        return '永久有效';
      }
      const hours = endTime * 24;
      return `${hours}小时售后`;
    },
    
    // 检查卡密是否被选中
    isSelected(carmine) {
      return this.selectedCarmines.some(item => 
        item.end_time === carmine.end_time && item.price === carmine.price
      );
    },
    
    // 获取当前价格（卡密商品从carmines获取）
    getCurrentPrice() {
      // 如果选中了卡密，计算按购买数量分配的总价格
      if (this.selectedCarmines.length > 0) {
        return this.calculateTotalPrice(this.quantity).toFixed(2);
      }
      
      // 如果只选择了规格但未选择卡密，显示该规格下最低价格的卡密价格
      if (this.selectedSpec && this.goodsInfo.carmines) {
        const specId = this.selectedSpec.id;
        const carmineData = this.goodsInfo.carmines[specId];
        if (carmineData) {
          let minPrice = null;
          Object.keys(carmineData).forEach(endTime => {
            const priceList = carmineData[endTime];
            if (Array.isArray(priceList)) {
              priceList.forEach(item => {
                if (item.price && item.allcount > 0) {
                  const price = parseFloat(item.price);
                  if (minPrice === null || price < minPrice) {
                    minPrice = price;
                  }
                }
              });
            }
          });
          return minPrice !== null ? minPrice.toFixed(2) : (this.selectedSpec.price || '0.00');
        }
      }
      // 如果carmines为空，则使用specs中的价格
      return this.selectedSpec ? (this.selectedSpec.price || '0.00') : (this.goodsInfo.price || '0.00');
    },
    
    // 智能分配卡密算法：优先分配最低价格的卡密，直到满足购买数量
    smartAllocateCarmines(quantity) {
      if (!this.selectedCarmines.length || quantity <= 0) {
        return [];
      }
      
      // 获取所有选中的卡密，按价格排序（从低到高）
      const sortedCarmines = [...this.selectedCarmines].sort((a, b) => 
        parseFloat(a.price) - parseFloat(b.price)
      );
      
      const allocation = [];
      let remainingQuantity = quantity;
      
      // 优先分配最低价格的卡密
      for (const carmine of sortedCarmines) {
        if (remainingQuantity <= 0) break;
        
        const availableStock = parseInt(carmine.allcount) || 0;
        if (availableStock <= 0) continue;
        
        // 计算这个卡密可以分配的数量
        const allocatedQuantity = Math.min(remainingQuantity, availableStock);
        
        if (allocatedQuantity > 0) {
          allocation.push({
            price: parseFloat(carmine.price),
            quantity: allocatedQuantity,
            end_time: carmine.end_time,
            totalPrice: parseFloat(carmine.price) * allocatedQuantity
          });
          
          remainingQuantity -= allocatedQuantity;
        }
      }
      
      return allocation;
    },
    
    // 计算总价格（根据智能分配的结果计算）
    calculateTotalPrice(quantity) {
      if (this.selectedCarmines.length === 0) {
        return 0;
      }
      
      // 使用智能分配算法
      const allocation = this.smartAllocateCarmines(quantity);
      
      // 计算总价格
      return allocation.reduce((total, item) => total + item.totalPrice, 0);
    },
    
    // 获取当前库存（卡密商品从carmines获取）
    getCurrentStock() {
      // 如果选中了卡密，显示选中卡密的总库存
      if (this.selectedCarmines.length > 0) {
        const totalStock = this.selectedCarmines.reduce((sum, item) => {
          return sum + (parseInt(item.allcount) || 0);
        }, 0);
        return totalStock > 0 ? totalStock : '0';
      }
      
      // 如果只选择了规格但未选择卡密，显示该规格下所有卡密的总库存
      if (this.selectedSpec && this.goodsInfo.carmines) {
        const specId = this.selectedSpec.id;
        const carmineData = this.goodsInfo.carmines[specId];
        if (carmineData) {
          let totalStock = 0;
          Object.keys(carmineData).forEach(endTime => {
            const priceList = carmineData[endTime];
            if (Array.isArray(priceList)) {
              priceList.forEach(item => {
                if (item.allcount) {
                  totalStock += parseInt(item.allcount) || 0;
                }
              });
            }
          });
          return totalStock > 0 ? totalStock : '无';
        }
      }
      return this.selectedSpec ? (this.selectedSpec.num || '0') : (parseInt(this.goodsInfo.stock) || 0);
    },
    
    // 构造carmines参数（订单类型为2时使用）- 使用智能分配结果
    buildCarminesParams(quantity) {
      const carminesArray = [];
      
      // 如果用户选择了卡密，使用智能分配算法
      if (this.selectedCarmines.length > 0) {
        const allocation = this.smartAllocateCarmines(quantity);
        
        // 将分配结果转换为订单参数格式
        for (const item of allocation) {
          carminesArray.push({
            price: item.price,
            num: item.quantity,
            end_time: item.end_time
          });
        }
        
        return carminesArray;
      }
      
      // 如果没有选择特定卡密，返回空数组（需要用户先选择）
      return carminesArray;
    },
    
    // 获取订单总价（供父组件调用）
    getOrderTotalPrice() {
      return this.calculateTotalPrice(this.quantity);
    },
    
    // 获取订单参数（供父组件调用）
    getOrderParams() {
      const allocation = this.smartAllocateCarmines(this.quantity);
      
      return {
        carmines: this.buildCarminesParams(this.quantity),
        totalPrice: this.calculateTotalPrice(this.quantity),
        quantity: this.quantity,
        selectedSpec: this.selectedSpec,
        selectedCarmines: this.selectedCarmines,
        allocation: allocation, // 详细的分配信息
        allocationSummary: this.getAllocationSummary(allocation) // 分配摘要
      };
    },
    
    // 获取分配摘要信息
    getAllocationSummary(allocation) {
      if (!allocation || allocation.length === 0) {
        return {
          totalQuantity: 0,
          totalPrice: 0,
          priceBreakdown: []
        };
      }
      
      const totalQuantity = allocation.reduce((sum, item) => sum + item.quantity, 0);
      const totalPrice = allocation.reduce((sum, item) => sum + item.totalPrice, 0);
      
      const priceBreakdown = allocation.map(item => ({
        price: item.price,
        quantity: item.quantity,
        subtotal: item.totalPrice,
        endTime: item.end_time
      }));
      
      return {
        totalQuantity,
        totalPrice,
        priceBreakdown
      };
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
        this.emitQuantityChange();
      }
    },
    
    // 增加数量
    increaseQuantity() {
      const maxStock = this.getCurrentStock();
      if (this.quantity < maxStock) {
        this.quantity++;
        this.emitQuantityChange();
      } else {
        uni.showToast({
          title: `您购买数量已超库存上限`,
          icon: 'none'
        });
      }
    },
    
    // 向父组件传递数量变化
    emitQuantityChange() {
      const orderParams = {
        quantity: this.quantity,
        totalPrice: this.calculateTotalPrice(this.quantity),
        carmines: this.buildCarminesParams(this.quantity)
      };
      this.$emit('quantity-change', this.quantity);
      this.$emit('order-params-change', orderParams);
    },
    
    // 验证卡密选择
    validateCarmineSelection(quantity) {
      if (this.selectedCarmines.length === 0) {
        return { valid: false, message: '请先选择卡密售价' };
      }
      
      // 计算选中卡密的总库存
      const totalStock = this.selectedCarmines.reduce((sum, item) => {
        return sum + (parseInt(item.allcount) || 0);
      }, 0);
      
      if (quantity > totalStock) {
        return { valid: false, message: '下单失败，选中卡密库存总量不足' };
      }
      
      return { valid: true, carmines: this.buildCarminesParams(quantity) };
    }
  }
}
</script>

<style scoped>
/* 卡密商品组件 */
.card-key-goods {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 商品规格选择 */
.product-duration-section {
  background-color: #ffffff;
  padding: 20px 16px;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 12px;
}

.option-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 0.8rem;
}

.option-btn {
  padding: 0.4rem 0.8rem;
  border: 2px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  transition: all 0.3s ease;
  cursor: pointer;
}

.option-btn.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.option-text {
  font-size: 14px;
  color: #666666;
}

.option-btn.active .option-text {
  color: #ff4757;
  font-weight: 500;
}

/* 卡密售价选择 */
.carmine-price-section {
  background-color: #ffffff;
  padding: 20px 16px;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.carmine-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}

.carmine-option {
  padding: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background-color: #ffffff;
  transition: all 0.3s ease;
  cursor: pointer;
}

.carmine-option.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.carmine-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.carmine-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.carmine-stock {
  font-size: 12px;
  color: #666666;
  border-radius: 12px;
}

.carmine-expire {
  font-size: 12px;
  color: #666666;
  background-color: #fff3cd;
  padding: 4px 8px;
  border-radius: 12px;
  border: 1px solid #ffeaa7;
}

.no-carmine-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.no-data-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  display: block;
  opacity: 0.5;
}

.no-data-text {
  font-size: 14px;
  color: #999999;
  line-height: 1.5;
}

.carmine-option.active .carmine-price {
  color: #ff4757;
}

.carmine-option.active .carmine-stock {
  background-color: #fff5f5;
  color: #ff4757;
}

.carmine-option.active .carmine-expire {
  background-color: #fff5f5;
  color: #ff4757;
  border-color: #ff4757;
}

/* 购买数量 */
.quantity-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  overflow: hidden;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.quantity-btn:hover {
  background-color: #f8f9fa;
}

.quantity-btn-text {
  font-size: 18px;
  color: #666666;
  font-weight: 500;
}

.quantity-value {
  font-size: 16px;
  color: #333333;
  margin: 0 16px;
  min-width: 24px;
  text-align: center;
  font-weight: 500;
}

/* 成交记录 */
.transaction-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.transaction-table {
  margin-top: 16px;
  border-radius: 8px;
}

.table-header {
  display: flex;
  background-color: #f5f5f5;
  padding: 12px 0;
  border-radius: 0.4rem;
}

.table-body {
  background-color: #ffffff;
}

.table-row {
  display: flex;
  padding: 0.25rem 0;
}

.table-row:last-child {
  border-bottom: none;
}

.even-row {
  background-color: #f9f9f9;
  border-radius: 0.5rem;
}

.header-cell, .body-cell {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.header-cell {
  color: #666666;
  font-weight: 500;
}

.body-cell {
  color: #333333;
}

.time-cell {
  flex: 1.2;
}

.price-cell {
  flex: 0.8;
}

.duration-cell {
  flex: 1;
}

/* 销售渠道 */
.channel-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.platform-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
  margin-bottom: 24px;
  justify-content: flex-start;
}

.platform-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.platform-icon {
  width: 1rem;
  height: 1rem;
  flex-shrink: 0;
}

.platform-text {
  font-size: 0.75rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.platform-item.supported .platform-text {
  color: #111111;
}

.platform-item.unsupported .platform-text {
  color: #999999;
}
</style>